<template>
  <div class="list" v-if="list.length">
    <div class="item" v-for="(item, index) in list" :key="item.chkitemCode">
      <ScoreMode :ref="'ScoreMode' + index" v-model="item.data" :cfg="item" show-throw-term />
    </div>
  </div>
</template>
<script>
// 全录入。inputMode 为 'ENTER_ALL'
import ScoreMode from './ScoreMode'
export default {
  name: 'AllInput',
  components: { ScoreMode },
  props: {
    value: { type: Array, default: () => [] },
    cfg: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      list: [],
      prevData: ''
    }
  },
  computed: {
    innerValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    cfg: {
      deep: true,
      immediate: true,
      handler() {
        this.initList()
      }
    },
    innerValue: {
      deep: true,
      immediate: true,
      handler(val) {
        const data = val || []
        const str = JSON.stringify(data)
        if (str === this.prevData) return
        this.prevData = str
        this.initList()
      }
    }
  },
  methods: {
    initList() {
      const cfgs = JSON.parse(JSON.stringify(this.cfg?.children || []))
      const data = JSON.parse(JSON.stringify(this.innerValue || []))
      if (!cfgs.length) return (this.list = [])

      const scoresMap = data.reduce((o, i) => !void (o[i.chkitemCode] = i) && o, {})
      cfgs.map((cfg, index) => {
        cfg.showThrowTerm = true
        cfg.data = scoresMap[cfg.chkitemCode] || {}
      })
      this.list = cfgs
    },
    async validate() {
      const list = this.list
      for (let i = 0; i < list.length; i++) {
        const name = 'ScoreMode' + i
        const ref = this.$refs[name]?.[0] || this.$refs[name]
        const valid = await ref?.validate().catch(() => false)
        if (!valid) return false
      }

      let data = list.map(i => i.data)
      data = JSON.parse(JSON.stringify(data))
      this.innerValue = data
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
.list {
  display: flex;
  flex-wrap: wrap;
}
.item {
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(black, 0.1);
  margin: 0 20px 20px 0;
}
</style>
